<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Classes\UploadImg;
use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\Shop\Clock;
use App\Models\Shop\GoodsClassify;
use App\Models\Shop\Recommend;
use App\Models\Shop\Store;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;

class StoreController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'name'          =>  'required|unique:shop_store',
        'address'       =>  'required'
    ];

    /**
     * 店铺管理
     * @return $this
     */
    public function getIndex()
    {
        $store = Store::paginate(20);
        return view('admin.shop.store')->with(['store' => $store]);
    }

    /**
     * 添加店铺
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getAdd()
    {
        return view('admin.shop.store-add');
    }
    public function postAdd(Request $request)
    {
        //验证
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreController@getAdd')->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $data = [
            'name'      =>  $request->input('name'),
            'address'   =>  $request->input('address')
        ];
        $data['display'] = 0;
        if($request->has('display'))
            $data['display'] = 1;
        //Create
        if (Store::create($data))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($data));
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\Shop\StoreController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\Shop\StoreController@getIndex'), 1);
    }

    /**
     * 修改
     * @param $id
     * @return $this
     */
    public function getEdit($id)
    {
        //获取店铺信息
        $store = Store::find($id);
        return view('admin.shop.store-edit')->with(['store' => $store]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $this->verifyFactor['name'] .= ',name,'.$id;
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreController@getEdit', ['id' => $id])->withErrors($verifyMsg);
        }
        //整理数据
        $data = [
            'name'      =>  $request->input('name'),
            'address'   =>  $request->input('address')
        ];
        if($request->has('display'))
        {
            $data['display'] = 1;
        }else{
            $data['display'] = 0;
        }

        //修改前的值
        $origin = Store::find($id)->toArray();
        //Update
        if (Store::where('id', $id)->update($data))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($data));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\Shop\StoreController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\Shop\StoreController@getEdit', ['id' => $id]), 1);
    }

    /**
     * 删除
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        //获取店铺
        $store = Store::find($id);
        $origin = $store->toArray();
        if (!empty($store))
        {
            if ($store->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * 推荐管理
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getRecommend($storeID)
    {
        //获取推荐位
        $store = Store::get()->keyBy('id');
        $recommend = Recommend::where('storeID', $storeID)->get();
        return view('admin.shop.store-recommend')->with(['recommend' => $recommend, 'store' => $store]);
    }

    /**
     * 推荐位管理
     * @param $id
     * @return $this
     */
    public function getRecommendEdit($id)
    {
        //获取
        $recommend = Recommend::find($id);
        $recommend->goods = explode(',', $recommend->goods);
        //获取商店信息
        $store = Store::find($recommend->storeID);
        $goodsClassify = GoodsClassify::orderBy('id', 'desc')->get(['id','name'])->keyBy('id');
        //获取商品
        $goods = DB::table('shop_store_goods')
            ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
            ->where('shop_store_goods.storeID', $recommend->storeID)
            ->where('shop_store_goods.display', 1)
            ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb', 'shop_goods.abstract')
            ->orderBy('shop_store_goods.id', 'desc')
            ->get();
        return view('admin.shop.store-recommend-edit')->with(['recommend' => $recommend, 'store' => $store, 'goodsClassify' => $goodsClassify, 'goods' => $goods]);
    }
    public function postRecommendEdit(Request $request, $id)
    {
        $this->verifyFactor = [
            'title'     =>  'required'
        ];
        //验证
        $verifyMsg = $this->verification($request->input());

        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreGoodsController@getAdd')->withInput()->withErrors($verifyMsg);
        }
        $display = 0;
        if($request->has('display'))
            $display = 1;
        //整理数据
        $data = [
            'title'     =>  $request->input('title'),
            'display'   =>  $display,
            'goods'     =>  $request->has('goodsID') ? implode(',', $request->input('goodsID')) : '',
            'thumb'     =>  $request->input('thumb')
        ];

        //Update
        if (Recommend::where('id', $id)->update($data))
        {
            //setLog
//            $this->setLog('update', json_encode($origin), json_encode($data));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\Shop\StoreController@postRecommendEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\Shop\StoreController@postRecommendEdit', ['id' => $id]), 1);
    }

    /**
     * 上传推荐位图片
     * @param UploadImg $uploadImg
     * @param Request $request
     */
    public function postUploadRecommend(UploadImg $uploadImg, Request $request)
    {
        if ($request->hasFile('icon'))
        {
            if ($request->file('icon')->isValid())
            {
                $avatar_file = $request->file('icon');
                $size = getimagesize($avatar_file);
                //"{"x":8.000000000000002,"y":8.000000000000002,"height":64,"width":64,"rotate":0}"
                $avatar_data = json_encode([
                    'x' =>  0,
                    'y' =>  0,
                    'height'    =>  $size[1],
                    'width'     =>  $size[0],
                    'rotate'    =>  0
                ]);
                $avatar_data_obj = json_decode(stripslashes($avatar_data));
                $date = date('Y-m-d', time());
                $uploadImg->savePath = config('imgUpdate.updatePath').$date.'/';
                //横纵比例
                $prefix = md5(time());
                $aspectRatio = [
                    [
                        'width'     =>  (int)$request->input('width'),
                        'height'    =>  (int)$request->input('height'),
                        'path'      =>  $prefix.'.png'
                    ]
                ];
                $backData = $uploadImg->upThumb($avatar_file, $avatar_data, $aspectRatio);
                if(count($backData) > 0)
                {
                    //返回数据
                    $backData['thumb'] = $date.'.'.$backData['thumb'];
                    $backData['msg'] = '上传成功！';
                    echo json_encode($backData);
                }
            }
        }
    }

    /**
     * 是否显示推荐
     * @param Request $request
     * @return string
     */
    public function postDisplayRecommend(Request $request)
    {
        $recommend = Recommend::find($request->input('id'));
        if(!empty($recommend))
        {
            $origin = $recommend->toArray();
            $recommend->display = $request->input('display');
            if ($recommend->save())
            {
                //setLog
//                $this->setLog('show', json_encode($origin), json_encode($request->except('_token')));
                return json_encode([
                    'code'      =>  1,
                    'message'   =>  getLang('Tips', 'updateSuccess')
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'message'   =>  getLang('Tips', 'updateFail')
        ]);
    }

    public function getClock($storeID)
    {
        //获取配送时间
        $clock = Clock::where('storeID', $storeID)->get();
        //获取商店信息
        $store = Store::find($storeID);
        return view('admin.shop.store-clock')->with(['clock' => $clock, 'store' => $store]);
    }

    public function getClockAdd($storeID)
    {
        $store = Store::find($storeID);
        return view('admin.shop.store-clock-add')->with(['store' => $store]);
    }
    public function postClockAdd(Request $request, $storeID)
    {
        $this->verifyFactor = [
            'time'      =>  'required',
            'price'     =>  'required|numeric|min:0',
            'term'      =>  'required|numeric|min:0',
            'priceTwo'  =>  'required|numeric|min:0'
        ];
        //验证
        $verifyMsg = $this->verification($request->input());

        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreGoodsController@getClockAdd', ['storeID' => $storeID])->withInput()->withErrors($verifyMsg);
        }
        $display = 0;
        if($request->has('display'))
            $display = 1;
        $data = [
            'storeID'       =>  $storeID,
            'time'          =>  $request->input('time'),
            'price'         =>  $request->input('price'),
            'term'          =>  $request->input('term'),
            'priceTwo'      =>  $request->input('priceTwo'),
            'display'       =>  $display
        ];

        //Create
        if (Clock::create($data))
        {
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\Shop\StoreController@getClock', ['storeID' => $storeID]), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\Shop\StoreController@getClock', ['storeID' => $storeID]), 1);

    }

    public function getClockEdit($id)
    {
        //获取时间配置信息
        $clock = Clock::find($id);
        //获取商店信息
        $store = Store::find($clock->storeID);
        return view('admin.shop.store-clock-edit')->with(['store' => $store, 'clock' => $clock]);
    }

    public function postClockEdit(Request $request, $id)
    {
        $this->verifyFactor = [
            'time'      =>  'required',
            'price'     =>  'required|numeric|min:0',
            'term'      =>  'required|numeric|min:0',
            'priceTwo'  =>  'required|numeric|min:0'
        ];
        //验证
        $verifyMsg = $this->verification($request->input());

        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreController@getClockEdit', ['id' => $id])->withInput()->withErrors($verifyMsg);
        }
        $display = 0;
        if($request->has('display'))
            $display = 1;
        $data = [
            'time'          =>  $request->input('time'),
            'price'         =>  $request->input('price'),
            'term'          =>  $request->input('term'),
            'priceTwo'      =>  $request->input('priceTwo'),
            'display'       =>  $display
        ];
        //Update
        if (Clock::where('id', $id)->update($data))
        {
            //setLog
//            $this->setLog('update', json_encode($origin), json_encode($data));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\Shop\StoreController@getClockEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\Shop\StoreController@getClockEdit', ['id' => $id]), 1);
    }

    public function postDisplayClock(Request $request)
    {
        $clock = Clock::find($request->input('id'));
        if(!empty($clock))
        {
            $origin = $clock->toArray();
            $clock->display = $request->input('display');
            if ($clock->save())
            {
                //setLog
//                $this->setLog('show', json_encode($origin), json_encode($request->except('_token')));
                return json_encode([
                    'code'      =>  1,
                    'message'   =>  getLang('Tips', 'updateSuccess')
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'message'   =>  getLang('Tips', 'updateFail')
        ]);
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'shop_store.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'shop_store.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'shop_store.delete',
                    'type'  =>  'Delete'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
